<template>
  <div class="app-container">
    <div class="purchas-war">
      <div class="ware-operation">
        <div class="ware-search">
          <!-- 搜索数据 -->
          <div class="search-input">
            <el-input
              class="input-data"
              placeholder="单据编码"
              v-model="searchForm.wmCode"
              clearable
            ></el-input>
            <el-input
              class="input-data"
              placeholder="销售单号"
              v-if="detailStatus == true"
              v-model="searchForm.ppNumber"
              clearable
            ></el-input>
            <el-input
              class="input-data"
              placeholder="物料编码"
              v-if="detailStatus == true"
              v-model="searchForm.invCode"
              clearable
            ></el-input>
            <el-input
              class="input-data"
              placeholder="物料名称"
              v-if="detailStatus == true"
              v-model="searchForm.invName"
              clearable
            ></el-input>
            <el-select
              class="picker-data"
              placeholder="单据状态"
              clearable
              v-model="searchForm.invoiceStatus"
              @change="invoiceStatusChange"
              v-if="detailStatus == false"
              @click.native="getInvoiceStatus()"
              style="margin-right: 15px; width: 150px"
            >
              <el-option
                v-for="dict in optionsinvoiceStatus"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
            <el-select
              class="picker-data"
              placeholder="业务状态"
              style="margin-right: 15px"
              v-if="detailStatus == false"
              clearable
              v-model="searchForm.workStatus"
            >
              <el-option
                v-for="dict in optionsworkStatus"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
            <el-date-picker
              v-model="valueDate"
              type="daterange"
              align="right"
              unlink-panels
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              style="width: 250px"
            >
            </el-date-picker>
          </div>
          <div class="search-btn">
            <el-button
              v-if="detailStatus == false"
              type="primary"
              v-hasPermi="['wm:checkin:query']"
              icon="el-icon-search"
              @click="searchList('bill')"
              >搜索
            </el-button>
            <el-button
              v-if="detailStatus == true"
              type="primary"
              v-hasPermi="['wm:checkin:query']"
              icon="el-icon-search"
              @click="searchList('detail')"
              >搜索
            </el-button>
          </div>
        </div>
      </div>
      <el-row :gutter="10" class="mb8" v-if="detailStatus == false">
        <div class="con-top">
          <div class="top-left">
            <el-col :span="1.5">
              <el-button
                type="primary"
                icon="el-icon-c-scale-to-original"
                size="mini"
                @click="detailView"
              >
                明细</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="primary"
                v-hasPermi="['wm:checkin:query']"
                plain
                icon="el-icon-menu"
                size="mini"
                @click="handleCheckleAll"
                >查询所有</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-select
                class="ware-sel"
                v-model="selectwarehouse"
                placeholder="仓库查询"
                @change="warehouseChange"
              >
                <el-option
                  v-for="item in optionswarehouse"
                  :key="item.uniqueId"
                  :label="item.name"
                  :value="item.code"
                >
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="primary"
                v-hasPermi="['wm:checkin:entity:add']"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="jumpAdd"
                >新增</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                v-hasPermi="['wm:checkin:remove']"
                plain
                icon="el-icon-delete"
                size="mini"
                @click="batchDelete"
                :disabled="batchStatus"
              >
                删除</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="success"
                v-hasPermi="['wm:checkin:permit']"
                plain
                icon="el-icon-bell"
                size="mini"
                @click="batchExamine"
                :disabled="batchStatus"
                >审核
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="info"
                v-hasPermi="['wm:checkin:revoke']"
                plain
                icon="el-icon-close-notification"
                size="mini"
                @click="batchDeExamine"
                :disabled="batchStatus"
                >反审核</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-printer"
                v-hasPermi="['wm:checkin:print']"
                size="mini"
                @click="printExamine"
                :disabled="batchStatus"
                >打印</el-button
              >
            </el-col>
          </div>
          <div class="top-right">
            <span
              :class="{ 'period-status': queryParams.period == '' }"
              v-if="selectwarehouse !== '' && nowPeriodYM !== ''"
              style="color: #515a6e; font-size: 14px; margin-right: 10px"
              >{{ this.timeZero(nowPeriodYM) }}</span
            >
            <el-link
              type="primary"
              v-hasPermi="['wm:checkin:period']"
              @click="jumpStrip('last')"
              :disabled="selectwarehouse == '' || queryParams.period == ''"
              >上一期间
            </el-link>
            <el-link
              type="primary"
              v-hasPermi="['wm:checkin:period']"
              @click="jumpStrip('next')"
              :disabled="selectwarehouse == '' || queryParams.period == ''"
              >下一期间
            </el-link>
          </div>
        </div>
      </el-row>
      <el-row
        :gutter="10"
        class="mb8"
        v-if="detailStatus == true"
        style="display: flex; align-items: center; position: relative"
      >
        <div class="con-top">
          <div class="top-left">
            <el-col :span="1.5">
              <el-button
                type="primary"
                icon="el-icon-document-remove"
                size="mini"
                @click="billView"
                >单据
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-menu"
                size="mini"
                @click="handleCheckleDetail"
                >查询所有</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-select
                class="ware-sel"
                v-model="selectwarehouse"
                placeholder="仓库查询"
                @change="warehouseChange"
              >
                <el-option
                  v-for="item in optionswarehouse"
                  :key="item.uniqueId"
                  :label="item.name"
                  :value="item.code"
                >
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="primary"
                v-hasPermi="['wm:checkin:entity:add']"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="jumpAdd"
                >新增</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
                v-hasPermi="['wm:checkin:export']"
                >导出</el-button
              >
            </el-col>
          </div>
          <div class="top-right">
            <span
              :class="{ 'period-status': queryDetail.period == '' }"
              v-if="selectwarehouse !== '' && nowPeriodYM !== ''"
              style="color: #515a6e; font-size: 14px; margin-right: 10px"
              >{{ this.timeZero(nowPeriodYM) }}</span
            >
            <el-link
              type="primary"
              v-hasPermi="['wm:checkin:period']"
              @click="jumpStrip('last')"
              :disabled="selectwarehouse == '' || queryDetail.period == ''"
              >上一期间
            </el-link>
            <el-link
              type="primary"
              v-hasPermi="['wm:checkin:period']"
              @click="jumpStrip('next')"
              :disabled="selectwarehouse == '' || queryDetail.period == ''"
              >下一期间
            </el-link>
          </div>
        </div>
      </el-row>
      <!-- 数据 -->
      <div class="ware-content">
        <div class="content-table">
          <el-table
            :data="tableData"
            border
            style="width: 100%"
            v-loading="loading"
            :height="maxHeight"
            @selection-change="handleSelectionChange"
            :row-class-name="tableRowClassName"
            v-if="detailStatus == false"
          >
            <el-table-column type="selection" width="50" align="center">
            </el-table-column>
            <el-table-column prop="wmCode" label="单据编码" align="center">
              <template v-slot="scope">
                <span class="red-scarlet">{{ scope.row.wmCode }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="invoiceDate"
              label="单据日期"
              align="center"
              sortable
            >
              <template v-slot="scope">
                <span>{{ scope.row.invoiceDate | inMaterTime }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="invoiceStatus"
              label="单据状态"
              align="center"
              width="120"
            >
              <template v-slot="scope">
                <div class="order-status">
                  <span
                    v-if="scope.row.invoiceStatus == '0'"
                    style="color: #e6a23c"
                    >{{ scope.row.params.sisName }}</span
                  >
                  <span
                    v-if="scope.row.invoiceStatus == '1'"
                    style="color: #67c23a"
                    >{{ scope.row.params.sisName }}</span
                  >
                  <span
                    v-if="scope.row.invoiceStatus == '2'"
                    style="color: #909399"
                    >{{ scope.row.params.sisName }}</span
                  >
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="params.iTName"
              label="单据类型"
              align="center"
            >
            </el-table-column>
            <el-table-column prop="params.wHName" label="仓库" align="center">
            </el-table-column>
            <el-table-column
              prop="params.swsName"
              label="业务状态"
              align="center"
              width="120"
            >
            </el-table-column>
            <el-table-column prop="checkDate" label="审核日期" align="center">
              <template v-slot="scope">
                <span v-if="scope.row.checkDate !== null">{{
                  scope.row.checkDate | inMaterTime
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" align="center">
              <template v-slot="scope">
                <div class="public-btn">
                  <el-link
                    type="primary"
                    v-hasPermi="['wm:checkin:entity:view']"
                    @click="jumpDetail(scope.row.wmCode)"
                    >查看
                  </el-link>
                  <el-link
                    type="success"
                    v-hasPermi="['wm:checkin:entity:edit']"
                    @click="jumpUpdate(scope.row.wmCode)"
                    :disabled="scope.row.invoiceStatus == '1'"
                    >编辑</el-link
                  >
                  <el-link
                    type="danger"
                    v-hasPermi="['wm:checkin:remove']"
                    :disabled="scope.row.invoiceStatus == '1'"
                    @click="handleDelete(scope.row)"
                  >
                    删除</el-link
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
          <!-- 明细列表 -->
          <el-table
            v-if="detailStatus == true"
            ref="tableDetailHeight"
            :data="detailTableData"
            border
            style="width: 100%"
            v-loading="detailLoading"
            :row-class-name="tableRowClassName"
            :height="detailMaxHeight"
            :key="tableKey2"
          >
            <el-table-column
              type="index"
              width="50"
              align="center"
              label="序号"
            >
            </el-table-column>
            <el-table-column
              prop="woCode"
              label="单据编码"
              align="center"
              width="130"
            >
              <template v-slot="scope">
                <div>
                  <span
                    style="color: #1890ff"
                    @click="jumpDetail(scope.row.wmCode)"
                    >{{ scope.row.wmCode }}</span
                  >
                </div>
              </template>
            </el-table-column>
            <el-table-column label="单据状态" align="center" width="100">
              <template v-slot="scope">
                <div class="order-status">
                  <span
                    v-if="scope.row.invoiceStatus == '0'"
                    style="color: #e6a23c"
                    >开立</span
                  >
                  <span
                    v-if="scope.row.invoiceStatus == '1'"
                    style="color: #67c23a"
                    >审核</span
                  >
                  <span
                    v-if="scope.row.invoiceStatus == '2'"
                    style="color: #909399"
                    >退回</span
                  >
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="ppNumber"
              label="销售单号"
              align="center"
              width="130"
            >
              <template v-slot="scope">
                <div>
                  <span
                    v-if="
                      scope.row.ppNumber !== null && scope.row.ppNumber !== ''
                    "
                  >
                    {{ scope.row.ppNumber }}</span
                  >
                  <span v-else><i class="el-icon-minus"></i></span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="invCode"
              label="物料编码"
              width="150"
              align="center"
            >
            </el-table-column>
            <el-table-column prop="invName" label="物料名称" align="center">
              <template v-slot="scope">
                <div>
                  <span
                    @click="handleDawer(scope.row)"
                    v-if="scope.row.wiQuantity > 0"
                    :style="
                      scope.row.quantity == scope.row.wiQuantity
                        ? 'color: #13ce66'
                        : 'color:#1890ff'
                    "
                    >{{ scope.row.invName }}</span
                  >
                  <span
                    @click="handleDawer(scope.row)"
                    v-else
                    style="color: #606266"
                    >{{ scope.row.invName }}</span
                  >
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="invAttribute"
              label="规格型号"
              width="150"
              align="center"
            >
            </el-table-column>

            <el-table-column
              prop="quantity"
              label="数量"
              align="center"
              width="150"
            >
              <template v-slot="scope">
                <div style="text-align: right">
                  <span>{{ scope.row.quantity }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="batchNumber"
              label="批号"
              align="center"
              width="120"
            >
            </el-table-column>
            <el-table-column
              prop="attribute"
              label="物料属性"
              width="200"
              align="center"
            >
            </el-table-column>

            <el-table-column
              prop="wiQuantity"
              label="出库数量"
              align="center"
              width="150"
            >
              <template v-slot="scope">
                <div style="text-align: right">
                  <span>{{ scope.row.wiQuantity }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="date"
              label="单据日期"
              align="center"
              width="100"
            >
              <template v-slot="scope">
                <span
                  v-if="
                    scope.row.invoiceDate !== null &&
                    scope.row.invoiceDate !== undefined
                  "
                  >{{ scope.row.invoiceDate | inMaterTime }}</span
                >
              </template>
            </el-table-column>
          </el-table>
          <!-- 详情抽屉 -->
          <el-drawer
            :title="drawerTitle"
            :visible.sync="drawer"
            :direction="direction"
            :before-close="handleClose"
            size="928px"
            class="po-drawer-detail"
          >
            <div class="drawer-detail-table">
              <el-table
                ref="tableDetailHeight"
                :data="drawerTableData"
                border
                style="width: 100%"
                v-loading="drawerTableLoading"
                :height="drawerTableMaxHeight"
                :row-class-name="tableRowClassName"
              >
                <el-table-column
                  type="index"
                  width="50"
                  align="center"
                  label="序号"
                >
                </el-table-column>
                <el-table-column
                  prop="code"
                  label="单据编码"
                  align="center"
                  width="110"
                >
                  <template v-slot="scope">
                    <div>
                      <span
                        style="color: #1890ff"
                        @click="handleViewBill(scope.row)"
                        >{{ scope.row.code }}</span
                      >
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="invoice_name"
                  label="单据类型"
                  align="center"
                  width="95"
                >
                </el-table-column>
                <el-table-column
                  prop="type_name"
                  label="业务类型"
                  align="center"
                  width="80"
                >
                </el-table-column>
                <el-table-column
                  prop="date"
                  label="单据日期"
                  align="center"
                  width="100"
                >
                </el-table-column>
                <el-table-column
                  prop="inv_code"
                  label="物料编码"
                  align="center"
                  width="100"
                >
                </el-table-column>
                <el-table-column
                  prop="inv_name"
                  label="物料名称"
                  align="center"
                >
                  <template v-slot="scope">
                    <div>
                      <span
                        >{{ scope.row.inv_name }}
                        {{ scope.row.inv_attribute }}</span
                      >
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="unit_name"
                  label="主计量"
                  align="center"
                  width="80"
                >
                </el-table-column>
                <el-table-column prop="quantity" label="数量" align="center">
                  <template v-slot="scope">
                    <div style="text-align: right">
                      <span>{{ scope.row.quantity }}</span>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-drawer>
        </div>
      </div>
    </div>
    <!-- 入库单据分页 -->
    <pagination
      v-if="total > 0 && detailStatus == false"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getMasterList"
    />
    <!-- 明细分页 -->
    <pagination
      v-if="detailTotal > 0 && detailStatus == true"
      :total="detailTotal"
      :page.sync="queryDetail.pageNum"
      :limit.sync="queryDetail.pageSize"
      @pagination="getDetailList"
    />
    <Billprint
      @batchPrint="getPrint($event)"
      :formInput="formInput"
      ref="saveDetail"
      v-if="billStatus"
      :key="billKey"
      :selectPrint="selectPrint"
      :BatchPrintData="BatchPrintData"
      :wmCodeArr="wmCodeArr"
    />
    <PrintPage
      :key="printKey"
      :printData="printData"
      v-if="printStatus"
      ref="startPrint"
    />
    <el-dialog title="提示" :visible.sync="open" width="23%">
      <div class="tip-box1">
        <span style="color: #515a6e">{{ tipSuccess }}</span>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Billprint from "../../components/Checkin/billprint.vue";
//打印组件
import PrintPage from "../../components/Checkin/printBatch";
import {
  dictMatching, //字典
  listMaster, //入库单据
  listDetail, //明细
  listWarehouses, //仓库列表
  deleteMaster, // 删除
  examineBill, //批量审核
  examineDeBill, //批量反审核
  seeMaster, // 查看入库单据
  blanceAll, //期间查询
  listLink, //关联查询
  exportDetail,
} from "../../api/checkin";
import print from "print-js"; //打印js
//并行请求
import axios from "axios";
export default {
  name: "Checkin",
  data() {
    return {
      // 遮罩层
      loading: true,
      //路由参数
      pathQuery: "",
      //仓库查询参数
      warehouseQuery: {
        invoiceType: "",
        bredVouch: "",
        workType: "",
      },
      // 开始时间/结束时间配置
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date(
                new Date(new Date().toLocaleDateString()).getTime()
              );
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date(
                new Date(new Date().toLocaleDateString()).getTime()
              );
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date(
                new Date(new Date().toLocaleDateString()).getTime()
              );
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      valueDate: "",
      //明细状态
      detailStatus: true,
      activeName: "first",
      // 入库单据查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        wmCode: "", //单据编码
        period: "",
        invoiceStatus: "", //单据状态
        warehouse: "", //仓库代码
        invoiceType: "",
        bredVouch: "",
        workType: "",
        workStatus: "", //单据状态
      },

      // 搜索表单
      searchForm: {
        wmCode: "", //单据编码
        startDate: "",
        endDate: "",
        workStatus: "", //单据状态
        invoiceStatus: "",
        invName: "", //物料名称
        invCode: "", //物料编码
        ppNumber: "",
      },
      //业务状态
      optionsworkStatus: [],
      //单据状态
      optionsinvoiceStatus: [],
      //仓库选择
      optionswarehouse: [],
      selectwarehouse: "",
      //区间查询按钮状态
      periodStatus: false,
      //所有可用期间
      periodDate: [],
      //当前期间年月
      nowPeriodYM: "",
      //当前期间
      nowPeriodData: null,
      //批量删除 批量审核 批量打印
      batchStatus: true,
      // 总条数
      total: 0,
      // 最大高度
      maxHeight: null,
      //入库信息
      tableData: [],
      // 已选单据编码
      wmCodeArr: [],
      // 批量打印数据
      BatchPrintData: [],
      //按钮显示开关
      isShow: "",
      // 批量打印单一表单数据
      formInput: {},
      //打印查看/组件状态
      billStatus: false,
      //查看/组件键值，用于批量打印刷新组件
      billKey: "",
      // 是否为批量打印
      selectPrint: "success",
      listenPrint: [],
      // 批量打印组件键值，用于重复点击打印刷新组件
      printKey: "",
      tipSuccess: "",
      // 批量打印组件状态
      printStatus: false,
      //批量打印弹框状态
      open: false,
      //明细 遮罩层
      detailLoading: true,
      //明细数据
      detailTableData: [],
      //小数位数
      decimal: "2",
      //明细查询参数
      queryDetail: {
        pageNum: 1,
        pageSize: 100,
        period: "",
        wmCode: "",
        invName: "",
        ppNumber: "",
        invCode: "", //物料编码
        warehouse: "", //仓库代码
        invoiceType: "",
        bredVouch: "",
        workType: "",
      },
      // 明细总条数
      detailTotal: 0,
      //明细表格key
      tableKey2: "",
      // 明细最大高度
      detailMaxHeight: null,
      //详情抽屉
      drawerTitle: "",
      drawer: false,
      isDrawer: null,
      direction: "rtl",
      drawerData: null,
      drawerTableData: [],
      drawerCustomer: {
        omOrderSalveList: [],
      },
      drawerMaterial: {}, //物料信息
      drawerTableLoading: true,
      drawerTableKey: "",
      drawerTableMaxHeight: null,
      materialStatus: false,
    };
  },

  created() {
    //赋值路由参数
    this.pathQuery = this.$route.query;
    // 仓库查询
    this.warehouseQuery = {
      invoiceType: this.pathQuery.invoiceType,
      bredVouch: this.pathQuery.bredVouch,
      workType: this.pathQuery.workType,
    };

    // 入库单据查询参数
    this.queryParams = {
      invoiceType: this.pathQuery.invoiceType,
      bredVouch: this.pathQuery.bredVouch,
      workType: this.pathQuery.workType,
      pageNum: 1,
      pageSize: 100,
    };

    // 入库明细查询参数
    this.queryDetail = {
      invoiceType: this.pathQuery.invoiceType,
      bredVouch: this.pathQuery.bredVouch,
      workType: this.pathQuery.workType,
      pageNum: 1,
      pageSize: 100,
    };

    // 初始化仓库
    this.getWorkStatus();
    this.getHouselList();
  },
  activated() {
    const refresh = this.$store.getters["stockStatus/getCheckinRefresh"];
    if (refresh == true && this.detailStatus == true) {
      this.$store.dispatch("stockStatus/setCheckinRefresh", false);
      this.getDetailList();
    } else if (refresh == true && this.detailStatus == false) {
      this.$store.dispatch("stockStatus/setCheckinRefresh", false);
      this.getMasterList();
    }
  },
  methods: {
    // 明细按钮
    detailView() {
      this.detailStatus = true;
      this.handleCheckleDetail();
    },

    //获取入库数据
    getMasterList() {
      this.loading = true;
      listMaster(this.queryParams).then((res) => {
        if (res.code == 200) {
          this.tableData = res.rows;
          if (res.rows.length > 0) {
            let list = JSON.parse(JSON.stringify(res.rows));
            let last = this.inMaterTime(list[0].invoiceDate),
              tag = 0;
            list.forEach((item, i) => {
              item.invoiceDate = this.inMaterTime(item.invoiceDate);
              if (list[i].invoiceDate !== last) {
                if (tag == 1) {
                  tag = 0;
                } else if (tag == 0) {
                  tag = 1;
                }
              }
              list[i].tag = tag;
              last = list[i].invoiceDate;
            });
            this.tableData = list;
            console.log(this.tableData);
          } else {
            this.tableData = [];
          }
          this.total = res.total;
          //最大高度
          this.maxHeight = `${document.documentElement.clientHeight}` - 270;
          this.loading = false;
        }
      });
    },

    // 获取业务状态
    getWorkStatus() {
      return new Promise((resolve) => {
        dictMatching("sys_work_status").then((res) => {
          if (res.code == 200) {
            this.optionsworkStatus = res.data;
            resolve();
          }
        });
      });
    },

    // 获取单据状态
    getInvoiceStatus() {
      dictMatching("sys_invoice_status")
        .then((res) => {
          if (res.code == 200) {
            this.optionsinvoiceStatus = res.data;
          }
        })
        .catch((err) => {
          this.msgError("获取单据状态失败");
        });
    },

    //改变单据状态
    invoiceStatusChange(value) {
      this.searchForm.invoiceStatus = value;
    },

    //仓库列表
    getHouselList() {
      listWarehouses(this.warehouseQuery).then((res) => {
        if (res.code == 200) {
          this.optionswarehouse = res.rows;
          if (this.optionswarehouse.length > 0) {
            this.warehouseChange(this.optionswarehouse[0].code);
            this.selectwarehouse = this.optionswarehouse[0].code;
          } else {
            this.loading = false;
          }
        }
      });
    },

    //点击仓库下拉
    handleWarehouse() {
      this.getHouselList();
    },

    // 仓库选择
    warehouseChange(code) {
      this.checkClearAll();
      this.queryParams.warehouse = code;
      this.queryDetail.warehouse = code;
      // 仓库配置
      let houseMsg = null;
      this.optionswarehouse.forEach((item) => {
        if (item.code == code) {
          houseMsg = item;
        }
      });
      if (houseMsg !== null) {
        if (houseMsg.configMap !== null) {
          if (houseMsg.configMap["precision.quantity"] !== "null") {
            this.decimal = houseMsg.configMap["precision.quantity"];
          }
        }
      }
      this.getPeriodList();
    },

    //可用结存
    getPeriodList() {
      blanceAll({ whCode: this.queryParams.warehouse }).then((res) => {
        if (res.code == 200) {
          this.periodDate = res.data;
          this.queryParams.period = res.data[res.data.length - 1].period;
          this.queryDetail.period = res.data[res.data.length - 1].period;
          this.nowPeriodYM = res.data[res.data.length - 1].period;
          this.nowPeriodData = res.data[res.data.length - 1];
          if (this.detailStatus == false) {
            this.getMasterList();
          } else {
            this.getDetailList();
          }
        }
      });
    },

    //变色
    tableRowClassName({ row, rowIndex }) {
      if (row.tag == 1) {
        return "warning-row";
      }
    },

    //搜索
    searchList(type) {
      this.queryParams.wmCode = this.searchForm.wmCode;
      this.queryParams.invoiceStatus = this.searchForm.invoiceStatus;
      // 日期转换
      if (
        this.valueDate !== undefined &&
        this.valueDate !== null &&
        this.valueDate.length > 0
      ) {
        if (this.detailStatus == false) {
          this.queryParams.startDate = this.parseTime(this.valueDate[0]);
          this.queryParams.endDate = this.setTime(this.valueDate[1]);
        } else {
          this.queryDetail.startDate = this.parseTime(this.valueDate[0]);
          this.queryDetail.endDate = this.setTime(this.valueDate[1]);
        }
      } else {
        if (this.detailStatus == false) {
          this.queryParams.startDate = "";
          this.queryParams.endDate = "";
        } else {
          this.queryDetail.startDate = "";
          this.queryDetail.endDate = "";
        }
      }
      if (type == "bill") {
        this.queryParams.wmCode = this.searchForm.wmCode;
        this.queryParams.workStatus = this.searchForm.workStatus;
        this.queryParams.invoiceStatus = this.searchForm.invoiceStatus;
        this.getMasterList();
      } else if (type == "detail") {
        this.queryDetail.wmCode = this.searchForm.wmCode;
        this.queryDetail.invName = this.searchForm.invName;
        this.queryDetail.invCode = this.searchForm.invCode;
        this.queryDetail.ppNumber = this.searchForm.ppNumber;
        this.getDetailList();
      }
    },

    /** 查询所有*/
    handleCheckleAll() {
      this.checkClearAll().then(() => {
        this.getMasterList();
      });
    },

    // 单据按钮
    billView() {
      this.detailStatus = false;
      this.handleCheckleAll();
    },

    // 清空单据/明细搜索条件
    checkClearAll() {
      return new Promise((resolve, reject) => {
        this.queryParams.pageNum = 1;
        this.queryParams.pageSize = 100;
        this.queryParams.wmCode = "";
        this.queryParams.workStatus = "";
        this.queryParams.invoiceStatus = "";
        this.queryParams.period = this.nowPeriodYM;
        this.queryParams.startDate = "";
        this.queryParams.endDate = "";
        this.valueDate = [];
        // 搜索表单
        this.searchForm = {
          startDate: "",
          wmCode: "",
          endDate: "",
          invoiceStatus: "",
          startDate: "",
          ppNumber: "",
          endDate: "",
          invName: "", //物料名称
          invCode: "", //物料编码
          workStatus: "", //业务状态
        };
        this.queryDetail.pageNum = 1;
        this.queryDetail.pageSize = 100;
        this.queryDetail.wmCode = "";
        this.queryDetail.invName = "";
        this.queryDetail.invCode = "";
        this.queryDetail.ppNumber = "";
        this.queryDetail.startDate = "";
        this.queryDetail.endDate = "";
        this.queryDetail.period = this.nowPeriodYM;
        resolve();
      });
    },

    // 获取明细
    getDetailList() {
      return new Promise((resolve, reject) => {
        this.detailLoading = true;
        listDetail(this.queryDetail).then((res) => {
          if (res.code == 200) {
            this.detailLoading = false;
            this.detailTotal = res.total;
            this.tableKey2 = Math.random();
            this.getDecimal();
            this.detailMaxHeight = null;

            if (res.rows.length > 0) {
              let list = JSON.parse(JSON.stringify(res.rows));
              let last = list[0].wmCode,
                tag = 0;
              list.forEach((item, i) => {
                if (list[i].wmCode !== last) {
                  if (tag == 1) {
                    tag = 0;
                  } else if (tag == 0) {
                    tag = 1;
                  }
                }
                list[i].tag = tag;
                last = list[i].wmCode;
              });
              this.detailTableData = list;
              this.getDecimal();
            } else {
              this.$refs["tableDetailHeight"].doLayout();
              this.detailTableData = [];
            }
            this.detailMaxHeight =
              `${document.documentElement.clientHeight}` - 270;
          }
        });
      });
    },

    //查询所有明细
    handleCheckleDetail() {
      this.checkClearAll().then(() => {
        this.getDetailList().then(() => {
          this.$refs.tableDetailHeight.clearFilter();
        });
      });
    },

    //导出
    handleExport() {
      const queryParams = this.queryDetail;
      this.$confirm("是否确认导出当前入库单明细?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportDetail(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },

    //新增
    jumpAdd() {
      this.$router.push({
        path: "/wm/stock/checkinadd",
        query: {
          open: "addStatus",
          whCode: this.selectwarehouse,
          bredVouch: this.$route.query.bredVouch,
          invoiceType: this.$route.query.invoiceType,
          workType: this.$route.query.workType,
          fmConfig: this.$route.query.fmConfig,
        },
      });
    },

    //批量选择
    handleSelectionChange(row) {
      this.wmCodeArr = [];
      if (row.length > 0) {
        this.batchStatus = false;
        row.forEach((obj) => {
          this.wmCodeArr.push({ wmCode: obj.wmCode });
        });
      } else {
        this.batchStatus = true;
      }
    },

    // 批量审核
    batchExamine() {
      this.$confirm("确认审核选中入库单", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return examineBill(this.wmCodeArr);
        })
        .then((res) => {
          if (res.code == 200) {
            this.msgSuccess("审核成功");
            this.getMasterList();
          }
        });
    },

    //批量反审核
    batchDeExamine() {
      this.$confirm("确认撤销审核选中入库单", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return examineDeBill(this.wmCodeArr);
        })
        .then((res) => {
          if (res.code == 200) {
            this.msgSuccess("撤销成功");
            this.getMasterList();
          }
        });
    },

    //批量删除
    batchDelete() {
      this.$confirm("确认删除选中入库单", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return deleteMaster(this.wmCodeArr);
        })
        .then((res) => {
          if (res.code == 200) {
            this.msgSuccess("删除成功");
            this.getMasterList();
          }
        });
    },

    //批量打印
    printExamine(wmCodeArr) {
      this.BatchPrintData = []; //组合打印数据
      this.printData = []; //最终打印数据
      this.tipSuccess = "单据加载中..."; //提示数据
      this.open = true; //显示提示
      //遍历已选择code通过bill组件处理打印数据
      this.wmCodeArr.forEach((code) => {
        seeMaster(code).then((res) => {
          if (res.code == 200) {
            this.formInput = res.data;
            this.billStatus = true;
            this.billKey = Math.random();
          }
        });
      });
    },

    /* 上下期间 */
    jumpStrip(type) {
      // 清空入库单据搜索
      this.searchForm = {
        startDate: "",
        wmCode: "",
        endDate: "",
        invoiceStatus: "",
      };
      let number = this.periodDate.indexOf(this.nowPeriodData);
      if (type == "next") {
        if (this.periodDate[number + 1] == undefined) {
          this.msgError("没有下一期间");
        } else {
          this.nowPeriodData = this.periodDate[number + 1];
          this.nowPeriodYM = this.periodDate[number + 1].period;
          this.queryParams.period = this.nowPeriodYM;
          this.queryDetail.period = this.nowPeriodYM;
          if (this.detailStatus == false) {
            this.getMasterList();
          } else {
            this.getDetailList();
          }
        }
      } else {
        if (this.periodDate[number - 1] == undefined) {
          this.msgError("没有上一期间");
        } else {
          this.nowPeriodData = this.periodDate[number - 1];
          this.nowPeriodYM = this.periodDate[number - 1].period;
          this.queryParams.period = this.nowPeriodYM;
          this.queryDetail.period = this.nowPeriodYM;
          if (this.detailStatus == false) {
            this.getMasterList();
          } else {
            this.getDetailList();
          }
        }
      }
    },

    //查看详情
    jumpDetail(wmCode) {
      this.$router.push({
        path: `/wm/stock/checkinview`,
        query: {
          detailCode: wmCode,
          open: "seeStatus",
          whCode: this.selectwarehouse,
          bredVouch: this.$route.query.bredVouch,
          invoiceType: this.$route.query.invoiceType,
          workType: this.$route.query.workType,
          fmConfig: this.$route.query.fmConfig,
        },
      });
    },

    // 编辑
    jumpUpdate(wmCode) {
      this.$router.push({
        path: `/wm/stock/checkinedit`,
        query: {
          detailCode: wmCode,
          open: "updateStatus",
          whCode: this.selectwarehouse,
          bredVouch: this.$route.query.bredVouch,
          invoiceType: this.$route.query.invoiceType,
          workType: this.$route.query.workType,
          fmConfig: this.$route.query.fmConfig,
        },
      });
    },

    //删除
    handleDelete(row) {
      let arr = [];
      arr.push({ wmCode: row.wmCode });
      this.$confirm("确认删除", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return deleteMaster(arr);
        })
        .then((res) => {
          if (res.code == 200) {
            this.msgSuccess("删除成功");
            this.getMasterList();
          }
        });
    },

    //关联详情
    handleDawer(row) {
      const self = this;
      if (this.drawer == false || this.isDrawer !== row) {
        this.isDrawer = row;
        this.drawer = true;
      } else if (this.drawer == true && this.isDrawer == row) {
        this.drawer = false;
        return false;
      }
      this.drawerTitle = row.wmCode + " " + "-" + " " + row.invName;
      this.drawerData = row;
      this.drawerTableLoading = true;
      //并行请求
      axios
        .all([
          //查询关联
          listLink({
            uniqueId: row.uniqueId,
          }),
        ])
        .then(
          axios.spread(function (resLink) {
            if (resLink.code == 200) {
              self.drawerTableData = resLink.data;
              self.getDecimal();
              self.drawerTableMaxHeight =
                `${document.documentElement.clientHeight}` - 175;
              self.drawerTableLoading = false;
            } else {
              self.msgError("查询关联物料信息失败");
            }
          })
        );
    },

    //上一条下一条
    btnForward(data, type) {
      let num = this.drawerCustomer.omOrderSalveList.indexOf(data);
      if (type == "next") {
        let addNum = num + 1;
        if (addNum < this.drawerCustomer.omOrderSalveList.length) {
          this.drawerMaterial = this.drawerCustomer.omOrderSalveList[addNum];
        } else {
          this.msgError("当前是最后一条");
        }
      } else {
        let reduceNum = num - 1;
        if (reduceNum >= 0) {
          this.drawerMaterial = this.drawerCustomer.omOrderSalveList[reduceNum];
        } else {
          this.msgError("当前是第一条");
        }
      }
    },

    //关闭抽屉
    handleClose() {
      this.drawer = false;
    },

    //关联跳转
    handleViewBill(row) {
      if (row.invoice == "po_invoice_type" && row.invoice_id == "2") {
        console.log(1);
        this.$router.push({
          path: "/po/purchase/checkinview",
          query: {
            detailCode: row.code,
            open: "seeStatus",
            workType: "",
            fmConfig: row.form_config,
          },
        });
      } else if (row.invoice == "wm_invoice_type" && row.invoice_id == "2") {
        this.$router.push({
          path: "/po/purchase/orderview",
          query: {
            detailCode: row.code,
            open: "seeStatus",
            workType: "",
            fmConfig: row.form_config,
          },
        });
      } else if (row.invoice == "po_invoice_type" && row.invoice_id == "2") {
        this.$router.push({
          path: "/po/purchase/checkinview",
          query: {
            detailCode: row.code,
            open: "seeStatus",
            workType: "",
            fmConfig: row.form_config,
          },
        });
      } else if (row.invoice == "po_invoice_type" && row.invoice_id == "3") {
        this.$router.push({
          path: "/po/purchase/rejectview",
          query: {
            detailCode: row.code,
            open: "seeStatus",
            workType: "",
            fmConfig: row.form_config,
          },
        });
      }
    },

    // 小数位数
    getDecimal() {
      if (this.detailTableData.length > 0) {
        this.detailTableData.forEach((item) => {
          if (item.price !== null && item.price !== undefined) {
            item.price = parseFloat(item.price).toFixed(this.decimal);
          }
          if (item.quantity !== null && item.quantity !== undefined) {
            item.quantity = parseFloat(item.quantity).toFixed(this.decimal);
          }
          if (item.amount !== null && item.amount !== undefined) {
            item.amount = parseFloat(item.amount).toFixed(this.decimal);
          }
          if (item.wiQuantity !== null && item.wiQuantity !== undefined) {
            item.wiQuantity = parseFloat(item.wiQuantity).toFixed(this.decimal);
          }
        });
      }
      if (this.drawerTableData.length > 0) {
        this.drawerTableData.forEach((item) => {
          if (item.quantity !== null && item.quantity !== undefined) {
            item.quantity = parseFloat(item.quantity).toFixed(this.decimal);
          }
        });
      }
    },

    //时间+23时59分59秒
    setTime(date) {
      date.setHours(date.getHours() + 23);
      date.setMinutes(date.getMinutes() + 59);
      date.setSeconds(date.getSeconds() + 59);
      let time = new Date(date);
      return (
        time.getFullYear() +
        "-" +
        (time.getMonth() + 1) +
        "-" +
        time.getDate() +
        " " +
        time.getHours() +
        ":" +
        time.getMinutes() +
        ":" +
        time.getSeconds()
      );
    },

    // 结存年月"
    timeZero(data) {
      let date = data.toString();
      let y = date.slice(0, 4),
        m = date.slice(4, 6);
      return y + "年" + m + "月";
    },

    getPrint(data) {
      this.listenPrint = data;
      setTimeout(() => {
        this.printData = JSON.parse(JSON.stringify(this.listenPrint));
        this.printData.forEach((obj) => {
          obj.invoiceDate = new Date(obj.invoiceDate);
        });
        this.printData.sort((a, b) => {
          //打印数排序
          return a.invoiceDate - b.invoiceDate;
        });
        this.printData.reverse();
        setTimeout(() => {
          this.printKey = Math.random();
          this.printStatus = true;
          this.open = false;
        }, 200);
      }, 500);
    },
    inMaterTime(date) {
      let time = new Date(date);
      return (
        time.getFullYear() + "-" + (time.getMonth() + 1) + "-" + time.getDate()
      );
    },
  },
  computed: {
    listenPrintCount() {
      return this.$store.getters["stockBillCount/getCount"];
    },
  },
  watch: {
    // 监听vuex打印数据完成数量
    listenPrintCount() {
      this.tipSuccess =
        "第" +
        this.$store.getters["stockBillCount/getCount"] +
        "张单据加载完成！";
    },
  },
  components: {
    Billprint,
    PrintPage,
  },
  filters: {
    //入库时间格式化
    inMaterTime(date) {
      let time = new Date(date);
      return (
        time.getFullYear() + "-" + (time.getMonth() + 1) + "-" + time.getDate()
      );
    },
  },
};
</script>
<style lang="scss">
.purchas-war {
  .el-drawer__wrapper {
    width: 958px;
    left: inherit;
  }
  .po-drawer-detail {
    .el-drawer.rtl {
      height: calc(100vh - 85px);
      top: auto;
    }

    .el-drawer__header {
      span {
        color: #333;
        font-size: 16px;
      }

      // text-align: center;
      margin-bottom: 12px;
    }

    .drawer-detail-table {
      padding: 0 15px;
    }

    .drawer-list-box {
      padding: 0 15px 0 0px;
      width: 100%;
      display: flex;
      justify-content: space-between;
      margin-bottom: 20px;

      .drawer-content {
        p {
          margin: 5px 0px 0px 0;
          label {
            font-size: 14px;
            color: #999;
            width: 70px;
            display: inline-block;
            font-weight: normal;
          }

          .la-width {
            width: 43px !important;
          }

          span {
            font-size: 14px;
            flex: 1;
          }
        }
        .drawer-box {
          .awer-l {
            float: left;
            width: 50%;
          }
          .content-t {
            display: flex;
          }
          .awer-r {
            float: left;
            width: 49%;
            margin-left: 1%;
            .con-price {
              p {
                display: flex;
                align-items: center;
                margin-right: 20px;
              }
            }

            .con-height {
              p {
                display: flex;
                height: 36px;
                span {
                  // height: 40px;
                  text-overflow: -o-ellipsis-lastline;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  display: -webkit-box;
                  -webkit-line-clamp: 2;
                  line-clamp: 2;
                  -webkit-box-orient: vertical;
                }
              }
            }
          }
        }
      }

      .drawer-number {
        flex: 0 1 20% !important;

        tr td:nth-of-type(1) {
          width: 50% !important;
        }
      }

      .drawer-table {
        flex: 1;
        margin-left: 15px;
        position: relative;
        .drawer-next {
          position: absolute;
          right: 0;
          font-size: 14px;
          top: 12px;
          z-index: 8;
        }
      }

      .inv-table {
        flex: 0 1 58%;
      }

      h2 {
        font-size: 14px;
        margin-top: 10px;
        margin-bottom: 5px;
        margin-left: 10px;
      }

      .box-bottom {
        margin-bottom: 15px;
      }

      p {
        margin: 8px 0;
        font-size: 15px;
      }

      .table-border {
        background-color: #f7f7f8;
        border-radius: 5px;
        padding: 8px 0;
        min-height: 130px;
      }

      table {
        width: 100%;

        td {
          text-align: left;
          padding: 2px 10px;
          font-size: 14px;
          // width: 50%;
        }

        tr td:nth-of-type(1) {
          color: #999;
        }
      }

      .table-left {
        tr td:nth-of-type(1) {
          width: 28%;
        }
      }

      .table-right {
        tr td:nth-of-type(1) {
          width: 20%;
        }
      }
    }
  }
  .el-link.is-underline:hover:after {
    border: none;
  }
  .period-status {
    opacity: 0.5;
  }
  .con-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;

    .top-right {
      display: flex;
      align-items: center;
    }
  }
  .el-range-editor--medium.el-input__inner {
    height: 32px;
    width: 100%;
  }
  .ware-sel {
    width: 150px;

    .el-input__inner {
      height: 28px;
      line-height: 28px;
    }

    .el-input--medium .el-input__icon {
      line-height: 28px;
    }
  }

  .el-input--medium .el-input__icon {
    line-height: 34px;
  }

  .el-table__header-wrapper th,
  .el-table .el-table__fixed-header-wrapper th {
    height: 35px;
  }

  .el-table .warning-row {
    background-color: #f5f7fa;
  }

  .el-table .yellow-row {
    .red-scarlet {
      color: #e6a23c;
    }
  }

  .has-gutter {
    .el-checkbox__inner {
      margin-right: 4px;
    }
  }

  .el-table tbody tr:hover > td {
    background: none !important;
  }

  .ware-operation {
    .ware-search {
      display: flex;
      margin-bottom: 20px;

      .search-input {
        display: flex;
        margin-right: 15px;

        .input-data {
          min-width: 200px !important;
          width: 200px;
        }

        .picker-data {
          min-width: 120px !important;
          width: 120px;
        }
        .el-range-editor--medium .el-range__icon,
        .el-range-editor--medium .el-range__close-icon,
        .el-range-editor--medium .el-range-separator {
          line-height: 24px;
        }

        .el-input {
          margin-right: 15px;
        }
      }
    }
  }

  .el-table th {
    height: 35px;
  }

  .el-table--medium th,
  .el-table--medium td {
    padding: 4px 0;
    padding-bottom: 3px;
  }

  .el-link--inner {
    margin-left: 3px;
    margin-right: 3px;
    font-size: 12px;
  }
}

.tip-box1 {
  text-align: center;
  width: 100%;

  span {
    color: #515a6e;
    font-size: 14px;
  }
}
.v-modal {
  display: none;
}

:focus {
  outline: 0;
}
</style>
